﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using Tesla.Graphics;
using Tesla.Xna.Util;
using XFG = Microsoft.Xna.Framework.Graphics;

namespace Tesla.Xna.Graphics {
    /// <summary>
    /// Implementation of an XNA 4.0 graphics adapter.
    /// </summary>
    public sealed class XNAGraphicsAdapter : IGraphicsAdapter {
        private int _adapterIndex;
        private XFG.GraphicsDevice _graphicsDevice;
        private XFG.GraphicsAdapter _adapter;
        private DisplayModeCollection _displayModes;
        private List<XFG.SurfaceFormat> _supportedTextureFormats;
        private List<XFG.SurfaceFormat> _supportedVertexTextureFormats;

        /// <summary>
        /// Gets the collection of supported display modes.
        /// </summary>
        public DisplayModeCollection SupportedDisplayModes {
            get { throw new NotImplementedException(); }
        }

        /// <summary>
        /// Gets the description of the device.
        /// </summary>
        public String Description {
            get {
                return _adapter.Description;
            }
        }

        /// <summary>
        /// Gets the device ID which identifies the particular chipset.
        /// </summary>
        public int DeviceId {
            get {
                return _adapter.DeviceId;
            }
        }

        /// <summary>
        /// Gets the adapter's revision number for the particular chipset its associated with.
        /// </summary>
        public int Revision {
            get {
                return _adapter.Revision;
            }
        }

        /// <summary>
        /// Gets the value that identifies the adapter's subsystem.
        /// </summary>
        public int SubSystemId {
            get {
                return _adapter.SubSystemId;
            }
        }

        /// <summary>
        /// Gets the value that identifies that chipset's manufacturer.
        /// </summary>
        public int VendorId {
            get {
                return _adapter.VendorId;
            }
        }

        /// <summary>
        /// Gets if this is the default adapter, always the first adapter.
        /// </summary>
        public bool IsDefaultAdapter {
            get {
                return _adapterIndex == 0;
            }
        }

        /// <summary>
        /// Gets the maximum size of a Texture1D resource.
        /// </summary>
        public int MaximumTexture1DSize {
            get {
                //Simulated by a 1-by-X Texture2D
                if(_graphicsDevice.GraphicsProfile == XFG.GraphicsProfile.HiDef) {
                    return 4096;
                } else {
                    return 2048;
                }
            }
        }

        /// <summary>
        /// Gets the maximum size (U,V) of a Texture2D resource.
        /// </summary>
        public int MaximumTexture2DSize {
            get {
                if(_graphicsDevice.GraphicsProfile == XFG.GraphicsProfile.HiDef) {
                    return 4096;
                } else {
                    return 2048;
                }
            }
        }

        /// <summary>
        /// Gets the maximum size (U,V,W) of a Texture3D resource.
        /// </summary>
        public int MaximumTexture3DSize {
            get {
                if(_graphicsDevice.GraphicsProfile == XFG.GraphicsProfile.HiDef) {
                    return 256;
                } else {
                    return 0; //Not supported
                }
            }
        }

        /// <summary>
        /// Gets the maximum size of a TextureCube resource.
        /// </summary>
        public int MaximumTextureCubeSize {
            get {
                if(_graphicsDevice.GraphicsProfile == XFG.GraphicsProfile.HiDef) {
                    return 4096;
                } else {
                    return 512;
                }
            }
        }

        /// <summary>
        /// Gets the maximum number of render targets that can be set to the
        /// device at once (MRT).
        /// </summary>
        public int MaximumMultiRenderTargets {
            get {
                if(_graphicsDevice.GraphicsProfile == XFG.GraphicsProfile.HiDef) {
                    return 4;
                } else {
                    return 1; //MRT not supported, just a single render target
                }
            }
        }

        /// <summary>
        /// Gets the maximum number of vertex buffers that can be set to the device at once.
        /// </summary>
        public int MaximumVertexStreams {
            get {
                return 16;
            }
        }

        /// <summary>
        /// Gets the maximum number of sampler states.
        /// </summary>
        public int MaximumSamplerStates {
            get {
                return 16;
            }
        }

        /// <summary>
        /// Gets the maximum number of vertex sampler states.
        /// </summary>
        public int MaximumVertexSamplerStates {
            get {
                if(_graphicsDevice.GraphicsProfile == XFG.GraphicsProfile.HiDef) {
                    return 4;
                } else {
                    return 0; //Vertex textures not supported
                }
            }
        }

        /// <summary>
        /// Queries if the specified surface format is valid for texture resources.
        /// </summary>
        /// <param name="surfaceFormat">Surface format</param>
        /// <param name="surfaceFormat">Surface format</param>
        /// <returns>True if valid, false otherwise</returns>
        public bool QueryTextureFormat(SurfaceFormat surfaceFormat, TextureDimensions texType) {
            return _supportedTextureFormats.Contains(XNAHelper.ToXNASurfaceFormat(surfaceFormat));
        }

        /// <summary>
        /// Queries if the specified surface format is valid for vertex texture resources.
        /// </summary>
        /// <param name="surfaceFormat">Surface format</param>
        /// <param name="surfaceFormat">Surface format</param>
        /// <returns>True if valid, false otherwise</returns>
        public bool QueryVertexTextureFormat(SurfaceFormat surfaceFormat, TextureDimensions texType) {
            if(_graphicsDevice.GraphicsProfile == XFG.GraphicsProfile.HiDef) {
                return _supportedVertexTextureFormats.Contains(XNAHelper.ToXNASurfaceFormat(surfaceFormat));
            } else {
                return false; //Vertex textures not supported
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="XNAGraphicsAdapter"/> class.
        /// </summary>
        /// <param name="graphicsDevice">The graphics device.</param>
        /// <param name="adapter">The adapter.</param>
        /// <param name="adapterIndex">Index of the adapter.</param>
        internal XNAGraphicsAdapter(XFG.GraphicsDevice graphicsDevice, XFG.GraphicsAdapter adapter, int adapterIndex) {
            _graphicsDevice = graphicsDevice;
            _adapter = adapter;
            _adapterIndex = adapterIndex;

            List<DisplayMode> list = new List<DisplayMode>();
            foreach(XFG.DisplayMode mode in adapter.SupportedDisplayModes) {
                DisplayMode display = new DisplayMode(mode.Width, mode.Height, XNAHelper.FromXNASurfaceFormat(mode.Format));
                if(list.Contains(display)) {
                    list.Add(display);
                }
            }
            _displayModes = new DisplayModeCollection(list);

            _supportedTextureFormats = new List<XFG.SurfaceFormat>(new XFG.SurfaceFormat[] {
                XFG.SurfaceFormat.Color, XFG.SurfaceFormat.Bgr565, XFG.SurfaceFormat.Bgra5551,
                XFG.SurfaceFormat.Bgra4444, XFG.SurfaceFormat.NormalizedByte2, XFG.SurfaceFormat.NormalizedByte4,
                XFG.SurfaceFormat.Dxt1, XFG.SurfaceFormat.Dxt3, XFG.SurfaceFormat.Dxt5
            });

            if(graphicsDevice.GraphicsProfile == XFG.GraphicsProfile.HiDef) {
                _supportedVertexTextureFormats = new List<XFG.SurfaceFormat>(new XFG.SurfaceFormat[] {
                    XFG.SurfaceFormat.Single, XFG.SurfaceFormat.Vector4, XFG.SurfaceFormat.Vector2,
                    XFG.SurfaceFormat.HalfVector2, XFG.SurfaceFormat.HalfVector4, XFG.SurfaceFormat.HalfSingle
                });

                _supportedTextureFormats.AddRange(new XFG.SurfaceFormat[] {
                    XFG.SurfaceFormat.Alpha8, XFG.SurfaceFormat.Rg32, XFG.SurfaceFormat.Rgba64,
                    XFG.SurfaceFormat.Rgba1010102, XFG.SurfaceFormat.Single, XFG.SurfaceFormat.Vector2,
                    XFG.SurfaceFormat.Vector4, XFG.SurfaceFormat.HalfSingle, XFG.SurfaceFormat.HalfVector2,
                    XFG.SurfaceFormat.HalfVector4
                });
            } 
        }

        /// <summary>
        /// Queries if the specified formats and sample counts are valid for the backbuffer.
        /// </summary>
        /// <param name="format">Surface format</param>
        /// <param name="depthFormat">Depth format</param>
        /// <param name="multiSampleCount">Sample count</param>
        /// <returns>True if a valid combination</returns>
        public bool QueryBackBufferFormat(SurfaceFormat format, DepthFormat depthFormat, int multiSampleCount) {
            XFG.SurfaceFormat xfgFormat;
            XFG.DepthFormat xfgDepthFormat;
            int xfgMulti;
            return _adapter.QueryBackBufferFormat(_graphicsDevice.GraphicsProfile, XNAHelper.ToXNASurfaceFormat(format),
                XNAHelper.ToXNADepthFormat(depthFormat), multiSampleCount, out xfgFormat, out xfgDepthFormat, out xfgMulti);
        }

        /// <summary>
        /// Queries if the specified format and sample counts are valid for a render target.
        /// </summary>
        /// <param name="format">Surface format</param>
        /// <param name="depthFormat">Depth format</param>
        /// <param name="multiSampleCount">Sample count</param>
        /// <returns>
        /// True if a valid combination
        /// </returns>
        public bool QueryRenderTargetFormat(SurfaceFormat format, DepthFormat depthFormat, int multiSampleCount) {
            XFG.SurfaceFormat xfgFormat;
            XFG.DepthFormat xfgDepthFormat;
            int xfgMulti;
            return _adapter.QueryRenderTargetFormat(_graphicsDevice.GraphicsProfile, XNAHelper.ToXNASurfaceFormat(format),
                XNAHelper.ToXNADepthFormat(depthFormat), multiSampleCount, out xfgFormat, out xfgDepthFormat, out xfgMulti);
        }

        /// <summary>
        /// Queries for the number of multisample quality levels are supported for the sample count.
        /// </summary>
        /// <param name="format">Specified format</param>
        /// <param name="multiSamplecount">Sample count</param>
        /// <returns>Number of supported quality levels</returns>
        public int QueryMultiSampleQualityLevels(SurfaceFormat format, int multiSamplecount) {
            //Doesn't seem to be a mechanism to check this
            if(QueryRenderTargetFormat(format, DepthFormat.None, multiSamplecount)) {
                return 1;
            }
            return 0;
        }
    }
}
